//
//  LiveEventChannelSupport.swift
//  liveplugin
//
//  Created by yunxiwangluo on 2020/5/16.
//

import UIKit

enum ResultType: Int {
    case MSG_INIT_LIVESTREAMING_ERROR = 0;//初始化直播出错
    case MSG_INIT_LIVESTREAMING_SUCCESS = 200;//初始化直播成功
    case MSG_START_LIVESTREAMING_ERROR = 3;//开始直播出错
    case MSG_STOP_LIVESTREAMING_ERROR = 4;//停止直播出错
    case MSG_START_PREVIEW_ERROR = 7;//打开视频预览失败
    case MSG_RTMP_URL_ERROR = 8; //RTMP URL连接出错
    case MSG_URL_NOT_AUTH = 9; //RTMP URL非法
    case MSG_START_PREVIEW_FINISHED = 23; //开始preview完成
    case MSG_START_LIVESTREAMING_FINISHED = 24; //开始直播完成
    case MSG_STOP_LIVESTREAMING_FINISHED = 25; //停止直播完成
    case MSG_SWITCH_CAMERA_FINISHED = 30; //切换摄像头完毕
    case MSG_SERVER_COMMAND_STOP_LIVESTREAMING = 32; //服务器下发停止直播的命令
    case MSG_URL_FORMAT_NOT_RIGHT = 41; //推流URL格式不正确（例如使用拉流url进行推流）
    case MSG_BAD_NETWORK_DETECT = 36; //连续一分钟视频帧率和码率都是0的消息
    case MSG_URL_IS_EMPTY = 42; //推流URL为空
}

class LiveEventChannelSupport:  NSObject,FlutterPlugin,FlutterStreamHandler{
    
    static let sharedInstance = LiveEventChannelSupport()
    
    var eventSink: FlutterEventSink?
    
    static func register(with registrar: FlutterPluginRegistrar) {
        
        let channel = FlutterEventChannel(name: "com.sunstar.liveplugin.viewControl_event", binaryMessenger: registrar.messenger())
        
        channel.setStreamHandler(self.sharedInstance);
  
    }
    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events;
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
         return nil
    }
    
    //发送错误给flutter
    func sendErrorToFlutter(error: Error) {
        //暂时没用到
//        if let sink = self.eventSink{
////            sink(self.createResult(type: .error, data: "String(describing: error)"))
//        }
    }
    
    //一般输出（例如连接成功等）
    func sendCommonDesToFlutter(type: ResultType,des: String){
        if let sink = self.eventSink{
            sink(self.createResult(type: type, data: des))
        }
    }
    

    func createResult(type:ResultType,data:Any)->Dictionary<String, Any>{
        return ["type":type.rawValue,"info":data]
    }
    
    
}
